package org.smart4j.framework.helper;

import org.smart4j.framework.annotation.Inject;
import org.smart4j.framework.util.ArrayUtil;
import org.smart4j.framework.util.CollectionUtil;
import org.smart4j.framework.util.ReflectionUtil;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * 依赖注入助手类
 *
 * @author zhang
 * @create 2016-11-01-11:03
 */

public final class IocHelper {

    static {
        Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();

        if(CollectionUtil.isNotEmpty(beanMap)){
            for(Map.Entry<Class<?>, Object> beanEntity : beanMap.entrySet()){
                Class<?> beanClass = beanEntity.getKey();
                Object beanInstance = beanEntity.getValue();
                //获取Bean类定义的所有成员变量
                Field[] beanFields = beanClass.getDeclaredFields();
                if(ArrayUtil.isNotEmpty(beanFields)){
                    for (Field beanField : beanFields) {
                        //是否带有Inject注解
                       if(beanField.isAnnotationPresent(Inject.class)){
                           Class<?> beanFieldClass = beanField.getType();
                           Object beanFieldInstance = beanMap.get(beanFieldClass);
                           if (beanFieldInstance != null) {
                               //通过反射初始化BeanField的值
                               ReflectionUtil.setField(beanInstance, beanField, beanFieldInstance);
                           }
                       }
                    }
                }
            }
        }
    }
}
